<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/19
 * Time: 10:54
 */

namespace backend\modules\manager\models;

use common\models\Product;
use Yii;
use yii\base\Model;

class ProductForm extends Model {

    /** 作品Id*/
    public $id;
    /** 作品标题 */
    public $title;
    /** 封面图 */
    public $banner_pic;
    /** 作品描述 */
    public $description;
    /** 是否显示品牌 0否 1是*/
    public $is_brand;
    /** 是否显示商家主页 0否 1是*/
    public $is_home;
    /** 背景音乐 */
    public $music;
    /** 页面切换 1上下切换 2折叠切换 3立体切换 */
    public $change_status;
    /** 上传图片 */
    public $pics;

    public $_product = false;

    /** 否 */
    const STATUS_N = 0;
    /** 是 */
    const STATUS_Y = 1;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /** 校验信息 */
            ['id', 'validateId'],
            [['pics','title'], 'required'],
            [['is_brand', 'is_home'], 'in', 'range' => [self::STATUS_N, self::STATUS_Y]],
        ];
    }

    /**
     * 认证信息
     */
    public function validateId($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (!$this->getProduct()) {
                $this->addError($attribute, 'Incorrect Id.');
            }
        }
    }

    public function getProduct()
    {
        if($this->_product === false){
            $this->_product = Product::findIdentity($this->id);
        }
        return $this->_product;
    }

    /**
     * Add Business
     */
    public function add()
    {
        /** 验证 */
        if($this->validate()){
            $product = $this->getProduct();
            $product->title = $this->title;
            $product->description = $this->description;
            $product->is_brand = $this->is_brand;
            $product->is_home = $this->is_home;
            $product->music = $this->music;
            $product->change_status = $this->change_status;
            $product->pics = $this->pics;
            $product->banner_pic = $this->banner_pic;
            /** 入库 */
            return $product->save(false);
        }
        return false;
    }
}